<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="功能房名" prop="roomName">
        <el-input v-model="queryParams.roomName" placeholder="请输入功能房名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['routine:room:add']">新增功能房</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :border="true" :data="roomList">
      <el-table-column label="序号" width="100" prop="id" />
      <el-table-column label="名称" width="170" prop="roomName" />
      <el-table-column label="容纳人数" width="100" prop="roomCapacity" />
      <el-table-column label="使用事项" width="175" prop="roomMatter" />
      <el-table-column label="功能房介绍" width="175" prop="roomInfo" />
      <el-table-column label="功能房用途" width="175" prop="roomPurp" />
      <el-table-column label="照片" width="175" prop="rtFuResourcesList">
        <template slot-scope="scope">
          <div class="images">
            <template v-if="scope.row.resPath && scope.row.resPath.length > 0">
              <el-image style="width: 100px; height: 100px;"
                :src="baseUrl + scope.row.resPath.split(',')[0]"></el-image>
            </template>
            <template v-else>
              <span>没有照片</span>
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="开放状态" width="100" prop="status">
        <template slot-scope="scope">
          <el-tooltip :content="'功能房开关'" placement="top">
            <el-switch v-model="scope.row.status == 0" active-text="关" active-color="rgb(36, 106, 221)"
              inactive-text="开" inactive-color="rgb(197, 197, 197)"
              @change="handleSwitchChange(scope.row.id, scope.row.status)"></el-switch>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <div style="display: flex;">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['routine:room:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['routine:room:remove']">删除</el-button>
            <el-button v-if="scope.row.status == 0" size="mini" type="text" icon="el-icon-delete"
              @click="handleCheckUsage(scope.row.roNo)">查看使用情况</el-button>
            <el-button v-if="scope.row.status == 0" size="mini" type="text" icon="el-icon-delete"
              @click="goReservation">查看预约记录</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改功能房弹出框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <div style="display: flex; justify-content: space-between; margin: 0 20px">
          <el-form-item label="名称" prop="roomName">
            <el-input v-model="form.roomName" placeholder="请输入" style="width: 200px" />
          </el-form-item>
          <el-form-item label="容纳人数" prop="roomCapacity">
            <el-input v-model="form.roomCapacity" placeholder="请输入" style="width: 200px;margin-right: 88px; " />
          </el-form-item>
        </div>
        <div style="display: flex; justify-content: space-between; margin: 0 20px">
          <div>
            <el-form-item label="开放状态" prop="status">
              <el-radio v-model="form.status" label="0">开放</el-radio>
              <el-radio v-model="form.status" label="1" style="margin-left: 63px;">关闭</el-radio>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="照片" prop="resPath">
              <image-upload v-model="form.resPath" />
            </el-form-item>
          </div>
        </div>
        <div style="margin-left: 50px;"><label>设置预约规则</label></div>
        <el-select v-model="selectweeklyTimeSlots" placeholder="请选择" style="margin-left: 50px; margin-top: 20px;"
          @change="handleSelectWeeklyTimeSlots">
          <el-option v-for="(item, index) in weeklyTimeSlots" :key="index" :label="item.soRule" :value="item.soRule">
          </el-option>
        </el-select>
        <div style=" display: flex; align-items: center; height:30px ; margin-top: 20px;" prop="rtFuSoltList">
          <div style="margin-top: 8px;"> <el-form-item label="使用日期"></el-form-item></div>
          <div>
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane v-for="(day, index) in weekdayslist" :key="index" :label="day.weekday"
                :name="day.weekday"></el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <div style="display:  flex;align-items: center; position: relative; margin-bottom:20px ; " prop="rtFuSoltList">
          <div><el-form-item label="使用时间"></el-form-item></div>
          <div style="display: flex; flex-direction: column; padding-bottom: 10px;">
            <div v-for="(item, indextime) in weekdayslist" :key="indextime"
              style="display: flex; align-items: center; margin-bottom: 12px;" v-if="item.weekday === activeName">
              <div>
                <div v-for="(timeSlot, slotIndex) in item.timeSlots"
                  style="display: flex; align-items: center; font-weight: bold;">
                  <div>{{ timeSlot.startTime }}-{{ timeSlot.endTime }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div style="display: flex; justify-content: space-between;">
          <el-form-item label="功能房介绍" prop="roomInfo">
            <el-input type="textarea" v-model="form.roomInfo" placeholder="请输入功能房介绍" style="width: 250px" />
          </el-form-item>
          <el-form-item label="功能房用途" prop="roomPurp">
            <el-input type="textarea" v-model="form.roomPurp" placeholder="请输入功能房用途" style="width: 250px" />
          </el-form-item>
        </div>
        <el-form-item label="使用事项" style=" padding-top: 80px;" prop="roomMatter">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入内容"
            v-model="form.roomMatter">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button @click="submitForm">提交</el-button>
      </div>
    </el-dialog>
    <!-- 查看详情弹出框 -->
    <el-dialog title="当前功能房使用情况" :visible.sync="getdetail" append-to-body style="position: absolute; top: 100px;">
      <div style="padding: 20px;">
        <!-- 检查是否有预约记录 -->
        <div v-if="fuDetailList.length > 0">
          <!-- 循环渲染每个星期的预约情况 -->
          <div style="margin-top: 20px;" v-for="(weekdayData, weekday) in fuDetailList" :key="weekday">
            <div style="display: flex; margin-bottom: 10px;">
              <strong style="margin-right: 20px;">日期</strong>
              <span>{{ weekdayData.rtweekday }} ({{ weekdayData.rtTime }})</span>
            </div>
            <!-- 循环渲染每个预约时间和使用人 -->
            <div>
              <div style="margin-right: 30px; display: flex;">
                <strong>时间</strong>
                <div v-for="(item, indexTime1) in weekdayData.timeSlots" :key="'time_' + indexTime1"
                  style="margin-left: 20px;">
                  {{ item.startTime }}-{{ item.endTime }}
                  <!-- {{ item }} -->
                </div>
              </div>
              <div style="margin-top: 10px;display: flex;">
                <strong>使用人</strong>
                <div v-for="(item1, index1) in weekdayData.timeSlots[0].nickNames" :key="'nickname_' + index1"
                  style="margin-left: 10px;">
                  {{ item1 }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else>
          <div style="text-align: center; margin-top: 10px;">当前功能房没有预约</div>
        </div>
        <!-- 按钮区域 -->
        <div style="position: absolute; bottom: 20px; right: 20px;">
          <el-button @click="getdetail = false">取消</el-button>
        </div>
        <div style="position: absolute; bottom: 20px; right: 10px;">
          <el-button @click="getdetail = false" style="margin-right: 10px;">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRoom, getRoom, delRoom, addRoom, updateRoom, updateStatus, getfuDetail, getfuTime } from "@/api/routine/room";
import { listSolt } from "@/api/routine/solt";
export default {
  name: "Room",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 功能房表格数据
      roomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roNo: null,
        roomName: null,
      },
      // 表单参数
      form: {},
      //提交预约参数
      roNo: '',
      rtPeople: '',
      rtPurpose: '',
      rtRole: '',
      rtTheme: '',
      rtTime: '',
      rtYuyue: '',
      // 表单校验
      rules: {
        roomName: [
          { required: true, message: "请输入功能房名", trigger: "blur" },
          { max: 50, message: "长度在 50 个字符以内", trigger: "blur" }
        ],
        roomCapacity: [
          { required: true, message: "请输入容纳人数", trigger: "blur" },
          { pattern: /^[0-9]*$/, message: "请输入数字", trigger: "blur" }
        ],
        roomInfo: [
          { required: true, message: "请输入功能房介绍", trigger: "blur" },
          { max: 200, message: "长度在 200 个字符以内", trigger: "blur" }
        ],
        roomPurp: [
          { required: true, message: "请输入功能房用途", trigger: "blur" },
          { max: 200, message: "长度在 200 个字符以内", trigger: "blur" }
        ],
        roomMatter: [
          { required: true, message: "请输入使用事项", trigger: "blur" },
          { max: 200, message: "长度在 200 个字符以内", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择开放状态", trigger: "change" }
        ],
        resPath: [
          { validator: this.validateImageUpload, trigger: "change" }
        ]
      },
      fuDetailList: [],
      textarea: '',
      activeName: '',
      radio: '',
      radio4: '',
      getdetail: false,
      timeValue: '',
      selectedRoomId: '',
      formattedDate: '',
      setRuleDialog: false,
      selectedRoomName: '',
      baseUrl: process.env.VUE_APP_BASE_API,
      selectDate: false,
      roType: '',
      innerVisible: false,
      rtFuResourcesTimeList: [],
      selectedWeekdays: '', // 选中的星期
      addTimes: [], // 添加的时间段
      weeklyTimeSlots: '',
      processedDataByWeekday: [],
      weekdayslist: [],
      selectweeklyTimeSlots: '',
      selectedSoNo: '',
      lists: []
    };
  },
  created() {
    this.getList();
    // 在Vue组件或其他代码中获取target的值
  },
  methods: {
    /** 查询功能房列表 */
    getList() {
      this.loading = true;
      listRoom(this.queryParams).then(response => {
        this.roomList = response.rows.map(item => ({
          id: item.id,
          roNo: item.roNo,
          roomName: item.roomName,
          roomImg: item.roomCapacity,
          roomInfo: item.roomInfo,
          roomPurp: item.roomPurp,
          roomMatter: item.roomMatter,
          status: item.status,
          roomRule: item.roomRule,
          roomCapacity: item.roomCapacity,
          resPath: (item.rtFuResourcesList.length > 0) ? item.rtFuResourcesList[0].resPath : null,
          rtFuSoltList: item.rtFuSoltList
        }));
        console.log(response)
        console.log(this.roomList);
        this.total = response.total;
        this.loading = false;
      })
    },

    // 取消按钮
    cancel() {
      this.selectedSoNo = '';
      this.selectweeklyTimeSlots = ''
      this.open = false;


      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        roomName: null,
        roomImg: null,
        roomInfo: null,
        roomPurp: null,
        status: null,
        roomCapacity: null,
        roomOpen: null,
        roomMatter: null,
      };
      this.radio = ''; // 重置单选按钮组
      this.resetForm("form"); // 重置表单验证状态
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.queryParams.pageSize = 10000;

      listSolt(this.queryParams).then(response => {
        // console.log(response);

        // 初始化存储时间段信息的数组
        const weeklyTimeSlots = [];

        // 使用 Map 来分组数据，key 是 soRule
        const groupByRule = new Map();

        // 遍历后端返回的数据 response.rows
        response.rows.forEach(slot => {
          // 如果当前规则不存在，创建一个新的对象存储该规则的时间段信息
          if (!groupByRule.has(slot.soRule)) {
            groupByRule.set(slot.soRule, {
              soRule: slot.soRule,
              soNo: slot.soNo, // 将 soNo 加入规则对象中
              weekdays: []
            });
          }

          // 获取当前规则的数据对象
          const ruleGroup = groupByRule.get(slot.soRule);

          // 查找当前星期是否已经存在
          let existingDay = ruleGroup.weekdays.find(item => item.weekday === slot.roWeekday);

          if (!existingDay) {
            // 如果不存在，创建一个新的对象存储该星期的时间段信息
            existingDay = {
              weekday: slot.roWeekday,
              timeSlots: []
            };
            ruleGroup.weekdays.push(existingDay);
          }

          // 将 roStartTime 和 roEndTime 存入对应的星期的时间段数组中
          existingDay.timeSlots.push({
            startTime: slot.roStartTime,
            endTime: slot.roEndTime
          });
        });

        // 将 Map 中的数据转换为所需的数组格式
        groupByRule.forEach(ruleGroup => {
          weeklyTimeSlots.push({
            soRule: ruleGroup.soRule,
            soNo: ruleGroup.soNo, // 将 soNo 添加到 weeklyTimeSlots 中的每个规则对象中
            weekdays: ruleGroup.weekdays
          });
        });

        console.log(weeklyTimeSlots); // 打印整理后的时间段数组

        if (this.weeklyTimeSlots.length > 0) {
          this.selectweeklyTimeSlots = this.weeklyTimeSlots[0].soRule;
          this.weekdayslist = this.weeklyTimeSlots[0].weekdays;
        }
        if (!this.selectedSoNo) {
          this.selectedSoNo = weeklyTimeSlots[0].soNo;
        }

        console.log(this.selectedSoNo)
        this.weeklyTimeSlots = weeklyTimeSlots;
        this.title = "添加功能房";
      }).catch(error => {
        console.error('Error fetching slot list:', error);
      });
    },

    detailUpdata(id) {
  getRoom(id)
    .then(response => {
      if (!response || !response.data || !response.data.rtFuSoltList) {
        console.error('Invalid response or missing data:', response);
        return;
      }

      this.form = response.data;

      if (response.data.rtFuResourcesList && response.data.rtFuResourcesList.length > 0) {
        this.form.resPath = response.data.rtFuResourcesList[0].resPath;
      } else {
        this.form.resPath = '';
      }
      console.log(this.form);

      this.open = true;
      this.lists = [];
      const addedRules = new Set();

      response.data.rtFuSoltList.forEach(slot => {
        if (!addedRules.has(slot.soRule)) {
          this.lists.push({
            soRule: slot.soRule,
            soNo: slot.soNo,
          });
          addedRules.add(slot.soRule);
        }
      });

      this.title = '修改功能房';
      if (this.weeklyTimeSlots.length > 0) {
        this.selectweeklyTimeSlots = this.lists[0].soRule;
      }
      if(this.selectedSoNo==''){
        this.selectedSoNo=this.lists[0].soNo
      }
    })
    .catch(error => {
      console.error('Error fetching room data:', error);
    });
}
,
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading=true
      const id = row.id || this.ids;
      this.detailUpdata(id);
      this.detailAllUpdata();
      this.loading=false
    },
    detailAllUpdata() {
  this.queryParams.pageSize = 10000;
  listSolt(this.queryParams)
    .then(response => {
      const weeklyTimeSlots = [];
      const groupByRule = new Map();

      response.rows.forEach(slot => {
        if (!groupByRule.has(slot.soRule)) {
          groupByRule.set(slot.soRule, {
            soRule: slot.soRule,
            soNo: slot.soNo,
            weekdays: []
          });
        }

        const ruleGroup = groupByRule.get(slot.soRule);
        let existingDay = ruleGroup.weekdays.find(item => item.weekday === slot.roWeekday);

        if (!existingDay) {
          existingDay = {
            weekday: slot.roWeekday,
            timeSlots: []
          };
          ruleGroup.weekdays.push(existingDay);
        }

        existingDay.timeSlots.push({
          startTime: slot.roStartTime,
          endTime: slot.roEndTime
        });
      });

      groupByRule.forEach(ruleGroup => {
        weeklyTimeSlots.push({
          soRule: ruleGroup.soRule,
          soNo: ruleGroup.soNo,
          weekdays: ruleGroup.weekdays
        });
      });

      this.open = true;
      console.log(weeklyTimeSlots);

      if (weeklyTimeSlots.length > 0) {
        this.selectweeklyTimeSlots = weeklyTimeSlots[0].soRule;
        this.weekdayslist = weeklyTimeSlots[0].weekdays;
      }
      this.weeklyTimeSlots = weeklyTimeSlots;
    })
    .catch(error => {
      console.error('Error fetching slot list:', error);
    });
}
,

    /** 提交按钮 */
    submitForm() {
      // 打印调试信息
      const imagePath = this.form.resPath;
      // 准备要提交的对象
      var obj = {
        resPath: imagePath
      };
      this.form.rtFuResourcesList = [];
      this.form.rtFuResourcesList.push(obj);
      console.log(this.selectedSoNo)
      this.form.roomRule = this.selectedSoNo
      // console.log(this.form.roomRule)
      console.log(this.form);
      // 触发表单验证并提交
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 修改功能房
            updateRoom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增功能房
            addRoom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.reset();
              this.getList();
            });
          }
        }
      });
    }
    ,
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除功能房编号为"' + ids + '"的数据项？').then(function () {
        return delRoom(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    //功能房状态开关
    handleSwitchChange(id, newValue) {
      console.log(newValue)
      const status = newValue == 0 ? 1 : 0;
      updateStatus(id, status).then(res => {
        this.$message.success("状态更新成功");
        this.getList()
      }).catch(error => {
        this.$message.error("状态更新失败：" + error.message);
      });
    },
    // 查看预约详情
    handleCheckUsage(roNo) {
      this.selectedRoomId = roNo;
      console.log(this.selectedRoomId);
      getfuDetail(this.selectedRoomId).then(res => {
        this.fuDetailList = res.data;
        console.log(res.data);

        // 使用对象来分组数据
        const groupedData = {};

        res.data.forEach(item => {
          const key = `${item.rtTime}_${item.rtweekday}`; // 以日期和星期几作为键

          if (!groupedData[key]) {
            groupedData[key] = {
              rtTime: item.rtTime,
              rtweekday: item.rtweekday,
              timeSlots: {}
            };
          }

          const timeSlotKey = `${item.roStartTime}-${item.roEndTime}`; // 以时间段作为内部键

          if (!groupedData[key].timeSlots[timeSlotKey]) {
            groupedData[key].timeSlots[timeSlotKey] = {
              startTime: item.roStartTime,
              endTime: item.roEndTime,
              nickNames: []
            };
          }

          groupedData[key].timeSlots[timeSlotKey].nickNames.push(item.nickName);
        });

        // 转换为数组形式便于渲染
        this.fuDetailList = Object.values(groupedData).map(item => {
          item.timeSlots = Object.values(item.timeSlots); // 转换时间段数据为数组形式
          return item;
        });

        console.log(this.fuDetailList);
      });

      this.getdetail = true;
    },

    goReservation() {
      this.$router.push('/reservation/index');
    },
    selectRulesDate(no) {
      this.roNo = no;
      console.log(this.No);
      this.selectDate = true;
    },
    deleteCity(index, slotIndex) {
      let targetItem = this.form.rtFuSoltList[index];
      targetItem.roWeektime = targetItem.roWeektime.split(',').filter((_, idx) => idx !== slotIndex).join(',');
      console.log(this.form.rtFuSoltList)
    },
    handleClick(tab, event) {
      console.log('点击的标签页名称:', tab.name);

    },
    handleSelectWeeklyTimeSlots() {
      console.log(this.selectweeklyTimeSlots);
      const selectedRule = this.weeklyTimeSlots.find(item => item.soRule === this.selectweeklyTimeSlots);
      if (selectedRule) {
        this.weekdayslist = selectedRule.weekdays;
        if (this.weekdayslist.length > 0) {
          this.activeName = this.weekdayslist[0].weekday;
        }
        this.selectedSoNo = selectedRule.soNo;
        console.log(this.selectedSoNo);
      }
    }
  }
};
</script>
<style scoped>
.imgaes {
  display: flex;
  flex-direction: row;
  justify-content: start;
  gap: 10px;
}

/* 去掉长分割线 */
::v-deep .el-tabs__nav-wrap::after {
  position: static !important;
}

/* 去掉下划线 */
::v-deep .el-tabs__active-bar {
  background-color: transparent !important;
}

/* //选中 */
::v-deep .el-tabs__item.is-active {
  color: rgb(70, 220, 146);
  opacity: 1;
}

/* //悬浮 */
::v-deep .el-tabs__item:hover {
  color: black;
  cursor: pointer;
  opacity: 1;
}

/* switch开关显隐 */
::v-deep .el-dialog {
  border-radius: 13px;
  min-width: 500px;
}

::v-deep .el-switch__core {
  width: 50px !important;
  height: 24px;
  border-radius: 100px;
  border: none;
}

::v-deep .el-switch__core::after {
  width: 20px;
  height: 20px;
  top: 2px;
}

::v-deep .el-switch.is-checked .el-switch__core::after {
  margin-left: -21px;
}

/*关闭时文字位置设置*/
::v-deep .el-switch__label--right {
  position: absolute;
  z-index: 1;
  left: 5px;
  margin-right: 0px;
  color: rgba(255, 255, 255, 0.9019607843137255);

  span {
    font-size: 13px;
    box-sizing: border-box;
    padding-left: 13px;
    color: #ffffff;
  }
}

/* 激活时另一个文字消失 */
::v-deep .el-switch__label.is-active {
  display: none;
}

/*开启时文字位置设置*/
::v-deep .el-switch__label--left {
  position: absolute;
  z-index: 1;
  right: 6px;
  margin-left: 0px;
  color: rgba(255, 255, 255, 0.9019607843137255);

  span {
    font-size: 13px;
    box-sizing: border-box;
    padding-right: 13px;
    color: #ffffff;
  }
}
</style>